import { useEffect, Suspense, useState, useRef, useCallback } from "react";
import { Canvas } from "@react-three/fiber";
import { OrbitControls, useGLTF, useAnimations } from "@react-three/drei";
import { Select, Input, Button } from "antd"; // 导入 Input 和 Button
import { useTranslation } from 'react-i18next';
import { useSpeechStore } from '../store/speechStore';
import { sendMessageToCoze } from '../utils/cozeApi'; // 导入 Coze API

// 仅保留三个不同动作，确保每个中文名字只对应一个动作
const MODEL_FILES = {
  happy: '/1111.glb',   // 开心挥手
  run: '/2222.glb',     // 跑步运动
  sad: '/3333.glb',     // 沮丧低落
};
// 显示标签采用固定中文，避免因 i18n 配置相同文案造成混淆
const ACTION_LABELS: Record<keyof typeof MODEL_FILES, string> = {
  happy: '开心挥手',
  run: '跑步运动',
  sad: '沮丧低落'
};

// 组件加载时预先缓存所有模型
// 预加载所有模型
Object.values(MODEL_FILES).forEach(file => {
  useGLTF.preload(file);
});
// 11111
const Model = ({ modelFile, currentAction, selectedAnimation, onAnimationsLoaded }: { 
  modelFile: string, 
  currentAction: string,
  selectedAnimation: string,
  onAnimationsLoaded: (animations: string[]) => void
}) => {
  // 加载3D模型文件，返回场景和动画数据
  const { scene, animations } = useGLTF(modelFile);
  const { actions } = useAnimations(animations, scene);
  
  
  useEffect(() => {
    // 当动画加载完成时，通知父组件 扫描模型中的所有可用动画
    const animationNames = Object.keys(actions).filter(key => actions[key]);
    if (animationNames.length > 0) {
      onAnimationsLoaded(animationNames);
    }
  }, [actions, onAnimationsLoaded]);
  
  useEffect(() => {
    console.log('模型文件:', modelFile);
    console.log('可用动画:', Object.keys(actions));
    console.log('当前动作:', currentAction);
    console.log('选中动画:', selectedAnimation);
    
    // 停止所有动画
    Object.values(actions).forEach(action => {
      if (action) {
        action.stop();
      }
    });
    
    // 播放选中的动画
    if (selectedAnimation && actions[selectedAnimation]) {
      actions[selectedAnimation].reset();
      actions[selectedAnimation].play();
      console.log('播放选中动画:', selectedAnimation);
    } else if (Object.keys(actions).length > 0) {
      // 如果没有选中动画，播放第一个可用的动画
      const firstAnimation = Object.values(actions).find(action => action);
      if (firstAnimation) {
        firstAnimation.reset();
        firstAnimation.play();
        console.log('播放第一个可用动画');
      }
    }
  }, [actions, modelFile, currentAction, selectedAnimation]);

  
  
  return <primitive object={scene} position={[0, -1, 0]} scale={[2, 2, 2]} />;
};

function Sandi() {
  const { t } = useTranslation();
  const [currentAction, setCurrentAction] = useState<string>('happy');
  const [currentModel, setCurrentModel] = useState<string>(MODEL_FILES.happy);
  const [selectedAnimation] = useState<string>('');


  // Coze 相关的状态
  const [userInput, setUserInput] = useState<string>('');
  const [conversationHistory, setConversationHistory] = useState<{ role: string; content: string }[]>([]);
  const [cozeResponse, setCozeResponse] = useState<string>('');
  const userId = useRef<string>(`user_${Date.now()}`).current; // 模拟用户ID

  // 使用分离选择器，避免 React 对外部存储的快照警告与循环渲染
  const characterAction = useSpeechStore(state => state.characterAction)
  const setCharacterAction = useSpeechStore(state => state.setCharacterAction)

  // 根据动作切换模型
  useEffect(() => {
    const modelFile = MODEL_FILES[currentAction as keyof typeof MODEL_FILES] || MODEL_FILES.happy;
    // 防止不必要的状态更新
    if (currentModel !== modelFile) {
      setCurrentModel(modelFile);
    }
  }, [currentAction, currentModel]);

  const handleActionChange = (value: string) => {
    console.log('切换动作到:', value);
    setCurrentAction(value);
    // 同步到全局，便于语音助手触发控制
    setCharacterAction(value)
  };

  const handleAnimationsLoaded = useCallback((animations: string[]) => {
    console.log('加载的动画:', animations);
  }, []);
// ss
  // 加加加jjjsssssss
// dd
  // 订阅全局角色动作，语音助手触发时切换组件动作
  useEffect(() => {
    if (!characterAction) return
    if (characterAction !== currentAction) {
      setCurrentAction(characterAction)
    }
    // 如果一致则不更新，避免无意义渲染
  }, [characterAction])

  // 取消嘴型联动逻辑，简化为仅播放模型动画

  const handleSendMessage = async () => {
    if (!userInput.trim()) return;

    const userMessage = { role: 'user', content: userInput };
    setConversationHistory(prev => [...prev, userMessage]);
    setUserInput('');

    try {
      const response = await sendMessageToCoze(userId, userInput);
      const botMessage = { role: 'bot', content: response };
      setConversationHistory(prev => [...prev, botMessage]);
      setCozeResponse(response); // 更新 Coze 响应状态
    } catch (error) {
      console.error('Error sending message to Coze:', error);
      const errorMessage = { role: 'bot', content: '与 Coze AI 通信失败。', };
      setConversationHistory(prev => [...prev, errorMessage]);
    }
  };

  // 根据 Coze 响应更新数字人动作
  useEffect(() => {
    if (cozeResponse) {
      const lowerCaseResponse = cozeResponse.toLowerCase();
      if (lowerCaseResponse.includes('happy') || lowerCaseResponse.includes('开心')) {
        setCurrentAction('happy');
        setCharacterAction('happy');
      } else if (lowerCaseResponse.includes('run') || lowerCaseResponse.includes('跑步')) {
        setCurrentAction('run');
        setCharacterAction('run');
      } else if (lowerCaseResponse.includes('sad') || lowerCaseResponse.includes('沮丧')) {
        setCurrentAction('sad');
        setCharacterAction('sad');
      } else {
        // 如果没有匹配到特定关键词，可以设置一个默认动作或者保持当前动作
        // setCurrentAction('happy');
        // setCharacterAction('happy');
      }
    }
  }, [cozeResponse, setCharacterAction]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', height: '100%' }}>
      {/* 动作控制选择器 */}
      <div style={{ 
        display: 'flex', 
        gap: '15px', 
        marginBottom: '15px',
        padding: '15px',
        backgroundColor: 'rgba(0,0,0,0.8)',
        borderRadius: '12px',
        color: 'white',
        alignItems: 'center',
        zIndex: 1000,
        flexWrap: 'wrap'
      }}>
        <span style={{ fontSize: '16px', fontWeight: 'bold' }}>{t('sandi.actions.title')}</span>
        <Select
          value={currentAction}
          style={{ width: 140 }}
          placeholder={t('sandi.actions.placeholder')}
          onChange={handleActionChange}
          options={Object.keys(MODEL_FILES).map(key => ({
            value: key,
            label: ACTION_LABELS[key as keyof typeof MODEL_FILES]
          }))}
        />
        
        {/* Coze 聊天界面 */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '300px' }}>
          <div style={{ height: '150px', overflowY: 'auto', border: '1px solid #ccc', padding: '10px', borderRadius: '8px', backgroundColor: '#f0f0f0', color: 'black' }}>
            {conversationHistory.map((msg, index) => (
              <div key={index} style={{ textAlign: msg.role === 'user' ? 'right' : 'left', marginBottom: '5px' }}>
                <span style={{ fontWeight: msg.role === 'user' ? 'bold' : 'normal', color: msg.role === 'user' ? '#007bff' : '#333' }}>
                  {msg.role === 'user' ? '你: ' : 'Coze: '}
                </span>
                {msg.content}
              </div>
            ))}
          </div>
          <Input
            value={userInput}
            onChange={(e) => setUserInput(e.target.value)}
            onPressEnter={handleSendMessage}
            placeholder="和数字人聊天..."
          />
          <Button type="primary" onClick={handleSendMessage}>发送</Button>
        </div>

        <span style={{ 
          fontSize: '14px', 
          color: '#4CAF50',
          fontWeight: 'bold'
        }}>
          {t('sandi.actions.current')}: {ACTION_LABELS[currentAction as keyof typeof MODEL_FILES] || currentAction}
        </span>
      </div>
      
      {/* 3D模型容器 */}
      <div style={{ width: "500px", height: "400px" }}>
        <Canvas
          camera={{ position: [0, 0, 5], fov: 30 }}
          style={{
            height: "100%",
            width: "100%",
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
          }}
        >
          <ambientLight intensity={1} />
          <directionalLight intensity={1} />
          <Suspense fallback={null}>
            <Model 
              modelFile={currentModel} 
              currentAction={currentAction}
              selectedAnimation={selectedAnimation}
              onAnimationsLoaded={handleAnimationsLoaded}
            />
          </Suspense>
          <OrbitControls />
        </Canvas>
      </div>
    </div>
  );
}

export default Sandi
